package com.mxpio.erp.equipment.provider;

import com.mxpio.erp.common.enums.CommonEnums;
import com.mxpio.erp.common.enums.EquipmentEnums;
import com.mxpio.erp.common.equipment.entity.EquipmentPersonGroup;
import com.mxpio.erp.common.equipment.entity.EquipmentPersonGroupDetail;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.query.Criterion;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.jpa.query.SimpleCriterion;
import com.mxpioframework.security.access.datascope.provider.DataScapeContext;
import com.mxpioframework.security.access.datascope.provider.DataScapeProvider;
import com.mxpioframework.security.util.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author : 吴盼盼
 * @Datetime : 2022/11/3 15:44
 * @Desc :
 * @Modor :  Modifytime:
 * @modDesc : engineerPersonGroupCode 当前登录人属于工程师组
 */
@Component
public class EngineerPersonGroupCodeProvider implements DataScapeProvider {
    @Override
    @Transactional(readOnly = true)
    public List<Criterion> provide(DataScapeContext context) {
        String loginUsername = SecurityUtils.getLoginUsername();
        List<Criterion> appendCriterions = new ArrayList<>();
        if (StringUtils.isBlank(loginUsername)){
            appendCriterions.add(new SimpleCriterion("createTime", Operator.EQ,new Date(0)));//如果未匹配到过滤条件，则增加一个不能正常匹配到数据的条件
            return appendCriterions;
        }
        List<EquipmentPersonGroup> personGroups = JpaUtil.linq(EquipmentPersonGroup.class)
                .exists(EquipmentPersonGroupDetail.class)
                    .equalProperty("groupId", "id")
                    .equal("userId",loginUsername)
                    .equal("isEnable", CommonEnums.YesNo.YES.getCode())
                .end()
                .equal("isEnable", CommonEnums.YesNo.YES.getCode())
                .equal("groupCategory", EquipmentEnums.PersonGroupCategory.GCS.getCode())//工程师 群组
                .list();
        if (personGroups.size()==0){
            appendCriterions.add(new SimpleCriterion("createTime", Operator.EQ,new Date(0)));//如果未匹配到过滤条件，则增加一个不能正常匹配到数据的条件
        }else {
            appendCriterions.add(new SimpleCriterion("engineerPersonGroupCode", Operator.IN, personGroups.stream().map(EquipmentPersonGroup::getGroupCode).collect(Collectors.toSet())));
        }
        return appendCriterions;
    }
}
